<template>
  <div class="goods-layout">
    <div class="info-back">
        <el-row :gutter="20">
            <el-col :span="15">
                <div class="back-icon"  @click="back()">
                    <i class="fa fa-arrow-left back" aria-hidden="true"></i>
                </div>
            </el-col>
            <el-col :span="4" class="btns">
                <el-button type="primary"  class="save red-btn" @click="confirm()">确定</el-button>

            </el-col>
        </el-row>

    </div>
    <div v-if="isMultiselect" class="items-list" id = "myDIV">

      <div class="el-check-ys">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
      </div>

      <el-checkbox-group
        v-model="checkList"
        @change="handleCheckedCitiesChange"
        >
        <div class="card-row" v-for="(item, index) in items">
            <el-checkbox :label="item" v-if="item.checked" checked>{{item.name}}</el-checkbox>
            <el-checkbox :label="item" v-else >{{item.name}}</el-checkbox>

        </div>
      </el-checkbox-group>
    </div>

    <div v-else class="items-list">
      <el-radio-group v-model="checkList">
        <div class="card-row" v-for="(item, index) in items">
            <el-radio :label="item">{{item.name}}</el-radio>


        </div>
      </el-radio-group>
    </div>
       <!--<span>Checked names: {{ checkList }}</span>-->

      <div class="pages">当前第{{currentPage}}页总共{{totalPage}}页</div>
      <div style=" width: 150px; margin: 0 auto;" v-if="allData">没有更多数据了</div>

  </div>

</template>
<script>
    export default {
        name: 'keepalive-false',
        data: function () {

            return {
                allData: false,
                allItems: [],
                items:[],
                selectedArray:[],
                noloadArray:[],
                checkList: [],
                selected:{},
                loading: false,
                isMultiselect: true,
                isHandler:false,
                param: '',
                rows: 20,//显示数量
                page: 1,//当前页数
                totalPage: 1,//总页数
                url: '',
                checkAll: false,
                isIndeterminate: true,
                loadAllItems: []


            }
        },
        computed: {
            currentPage: function () {

                if (this.page < this.totalPage) {

                    return this.page;
                } else {
                    return this.totalPage;
                }
            }
        },

        mounted: function () {
            if(this.$route.params.currentSelected){
                this.noloadArray = this.$route.params.currentSelected;
            }
            this.checkList=[];
            this.$$("#content").scrollTop(0)
            this.loadMore();
            let self = this;
            this.$$("#content").on('scroll', function (e) {
                var scrollTop = self.$$("#content").scrollTop();
                var innerHeight = self.$$("#content").innerHeight();
                var scrollHeight = self.$$("#content").scrollHeight();
                if (scrollTop + innerHeight >= scrollHeight) {
                    self.page++;
                    if (self.page > self.totalPage) {
                        return;
                    }

                    self.loadMore();
                    // console.log('*(******************' + self.page)
                }
            });

            document.getElementById("myDIV").addEventListener('wheel', function (e) {
                if (e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0) {
                    // console.log(e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0)
                    self.page++;

                    self.loadMore();
                }
            });
        },
        methods: {
           handleCheckAllChange(event) {
            // console.log(12)
              //  console.log(event.target.checked)
              this.checkList = event.target.checked ? this.items:[];
              this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {
            // console.log(34)
              let checkedCount = value.length;
              this.checkAll = checkedCount === this.items.length;
              this.isIndeterminate = checkedCount > 0 && checkedCount < this.items.length;
            },
            conversion: function (result, flag) {
              // console.log(result);
              var resultArray = [];
              // console.log(result.length)

              //拼凑成只有id和name的对象数组
              for(var i=0; i<result.length; i++){
                var resultObj = {};
                resultObj.id = result[i].id;

                if(this.$route.params.toFlag == "selectRights"){
                  resultObj.name = result[i].remark;
                }else {
                  resultObj.name = (result[i].name).trim();
                }

                resultArray.push(resultObj);


              }
              console.log("========================>1")


              this.allItems = resultArray; //每次加载的量

    //          this.loadAllItems.push.apply(this.loadAllItems,resultArray);


              var selectedArray =  this.noloadArray;
              // console.log(selectedArray.length);
              for(var i=0; i<selectedArray.length; i++){
                for(var j=0; j<this.allItems.length; j++){
                  //如果是选择经手人时，只有name没有id
                  if(this.isHandler == true){
                    if(this.allItems[j].name == selectedArray[i].name){
                     if(this.isMultiselect == true){
                        this.allItems[j].checked = true;
                      }
                      else {
                        this.checkList = this.allItems[j];
                      }
                    }
                    else {
                      // console.log("=========没有选择的")
                    }
                  }
                  // 不是选择经手人
                  else {
                    if(this.allItems[j].id == selectedArray[i].id){

                      console.log()

                      if(this.isMultiselect == true){
                        this.allItems[j].checked = true;



                      }
                      else {
                        this.checkList = this.allItems[j];
                      }

                    }
                  }

                 }
              }

                console.log("============2")
                console.log(selectedArray);
                console.log(this.loadAllItems)

                for( let item of this.allItems){
                    this.noloadArray =  this.noloadArray.filter((nitem)=>{
                        if(nitem.id!=item.id){
                            return nitem;
                        }
                    })



                }



                console.log(this.noloadArray)

              if(flag == "loadMore"){

                this.allItems.forEach(item => {

                  this.items.push(item);
                });
              }
              else {

                this.items = this.allItems;
              }

            },
            back: function () {
              console.log("========>back");
              // console.log(this.$route)
              this.$router.push({
                name: this.$route.params.backUrlName,
                path: this.$route.params.toFlag + this.$route.query,
                params: {
                  flag: 'back',
                  info: this.$route.params.info
                },
                query: this.$route.query
              });
            },
            confirm: function () {
              this.toStr();

              this.selected.isNewSelected = true;
              this.$router.push({
                name: this.$route.params.backUrlName,
                path: this.$route.params.toFlag + this.$route.query,
                params: {
                  flag: this.$route.params.toFlag,
                  selected: this.selected,
                  info: this.$route.params.info
                },
                query: this.$route.query
              });

            },

            toStr: function () {
              console.log("==========================sdfjsdkfjlksdf");
               console.log(this.checkList);
               console.log(this.noloadArray)
              if(this.checkList.length == 0 && this.noloadArray.length == 0){
                this.selected = [];
                return;
              }
              var selectedData = this.checkList;
              var selectedIds = [];
              var selectedNames = [];

              var noloadArray = [];
              var newSelected = [];


              if(this.isMultiselect == true){
                noloadArray =this.noloadArray;
                if(noloadArray.length>0) {
                    newSelected = selectedData.concat(noloadArray);
                }else{
                    newSelected= selectedData;
                }
              }


              // console.log(JSON.stringify(newSelected));

              newSelected.forEach(item => {
                if(item.remark){
                  item.name = item.remark;
                }
              });

               console.log(JSON.stringify(newSelected));


              // console.log(uniqNewSelected)

              if(this.isMultiselect == true){
                // console.log("===================>多选")
                for(var i=0; i<newSelected.length; i++){
                  // console.log(uniqNewSelected[i]);
                  selectedIds.push(newSelected[i].id);
                  selectedNames.push(newSelected[i].name);
                }
              }else {
                // console.log("===================>单选")
                if(this.checkList){
                  selectedIds.push(this.checkList.id);
                  selectedNames.push(this.checkList.name);
                }
              }

              // console.log(selectedIds);
              // console.log(selectedNames);

              var strSelectedIds = selectedIds.toString();
              var strSelectedNames = selectedNames.toString();
              // console.log(strSelectedIds);
              // console.log(strSelectedNames);

              this.selected.name = strSelectedNames;
              this.selected.id = strSelectedIds;

              // console.log(this.selected)
            },

            loadMore: function () {
              console.log("===================>loadMore")
                console.log(this.$route);
                this.isMultiselect = this.$route.params.isMultiselect;
                this.isHandler = this.$route.params.isHandler;

                this.url = this.$route.params.url;
                console.log(this.url)
                if (this.page <= this.totalPage) {
                    let url = '';
                    if (this.url.indexOf("?") >= 0) {
                      url = this.url + "&rows=" + this.rows + "&page=" + this.page
                    }
                    else {
                      url = this.url + "?rows=" + this.rows + "&page=" + this.page
                    }
                    let self = this;
                    self.loading = true;
                    this.$axioxs({
                       method: 'get',
                       url: url
                    })
                    .then(function (res) {
                            self.allItems = res.data.records;
                            self.totalPage = res.data.totalPage;
                            self.conversion(res.data.records,"loadMore");
                            self.loading = false;
                        })
                        .catch(function (error) {
                          console.log(error);
                          self.$message({
                              showClose: true,
                              type: 'error',
                              message: error,
                              onClose:function () {
                                self.loading = false;
                              }
                          });

                        });
                }
            }
        }

    }
</script>

<style scoped>
.card-row{
  background-color: #fff;
  padding: 10px 20px;
  border-top: 1px solid #cacaca;
  border-bottom: 1px solid #cacaca;
  margin-top: 10px;
}

.back{
  cursor: pointer;
}

.info-back{
  width: 100%;
  background-color: #fff;
  position: fixed;
  z-index: 999;
  box-shadow: 1px 3px 8px #cacaca;
}

.el-radio-group{
    display: block;
}

.el-radio, .el-checkbox{
  display: block;
}

.items-list{
  padding-top: 50px;
}

.el-check-ys{
  padding: 10px 0px 0px 20px;
}

.pages {
    position: fixed;
    bottom: 0;
    text-align: center;
    width: 70%;
    margin: 0 auto;
    /* background: black; */
    z-index: 20;
    height: 20px;
    opacity: 0.5;
    font-size: 9px;
}


</style>
